

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_ui/src/components/ListItem.dart';

import '../FormCreator.dart';

class FormTextControl extends StatefulWidget {
  final FormControlContext controlContext; 

  FormTextControl({Key key, this.controlContext }) :
    super(key: key);

  @override
  _FormTextControlState createState() => _FormTextControlState();
}

class _FormTextControlState extends State<FormTextControl> {
  TextEditingController controller;

  @override
  void initState() {
    super.initState();
    controller = TextEditingController(text: widget.controlContext.value);
  }

  @override
  void dispose() { 
    controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> props = widget.controlContext.mergedProps;
    if(controller.text != widget.controlContext.value) controller.text = widget.controlContext.value;
    FormCreatorHandler formHandler = FormCreatorState.of(context);
    
    return ListItem(
      title: props["title"] ??= "",
      subtitle: props["subtitle"] ??= "",
      titleStyle: props["titleStyle"],
      subtitleStyle: props["subtitleStyle"],
      child: TextField(
        controller: controller,
        obscureText: props["obscureText"]??=false,
        onSubmitted: (String value)=> formHandler.changeValue(widget.controlContext.copyWith(value: value, context: context)),
        onChanged: (String value)=> formHandler.changeValue(widget.controlContext.copyWith(value: value, context: context)),
        keyboardType: props["keyboardType"] ??= TextInputType.text,
        textInputAction: props["textInputAction"] ??= TextInputAction.done,
        inputFormatters: props["inputFormatters"],
        maxLength: props["maxLength"],
        decoration: InputDecoration(
          hintText: props["placeholder"] ??= "",
          hintStyle: props["placeholderStyle"],
          helperText: props["errorText"],
          helperStyle: TextStyle(color: Colors.red)
        ),
      ),
    );
  }
}
